export class ChatWebSocket {
  constructor(url, onMessage, onOpen, onClose, onError) {
    this.url = url;
    this.onMessage = onMessage;
    this.onOpen = onOpen;
    this.onClose = onClose;
    this.onError = onError;
    this.ws = null;
  }

  isConnected() {
    return this.ws && this.ws.readyState === WebSocket.OPEN;
  }

  connect() {
    this.socket = new WebSocket(this.url);

    this.socket.onopen = () => {
      console.log("WebSocket 连接已打开");
      if (this.onOpen) this.onOpen();
    };

    this.socket.onmessage = (event) => {
      const data = JSON.parse(event.data);
      if (this.onMessage) this.onMessage(data);
    };

    this.socket.onerror = (error) => {
      console.error("WebSocket 错误:", error);
      if (this.onError) this.onError(error);
    };

    this.socket.onclose = () => {
      console.log("WebSocket 连接已关闭");
      if (this.onClose) this.onClose();
    };
  }

  sendMessage(message) {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(JSON.stringify({ message }));
    } else {
      console.error("WebSocket 未连接，无法发送消息");
    }
  }

  close() {
    if (this.socket) {
      this.socket.close();
    }
  }
}